package com.fengye.algorithms.leecode;

import com.fengye.algorithms.leecode.common.ListNode;

/**
 * @Author fengye
 * @Date 2023/4/8 9:30
 **/
public class AddTwoNumbers02 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null) {
            return l2;
        }
        if(l2 == null){
            return l1;
        }
        ListNode res = new ListNode();
        ListNode head = res;
        int temp = 0;
        while (l1 != null || l2 != null) {
            int a = 0;
            if(l1 != null) {
                a = l1.val;
            }
            int b = 0;
            if(l2 != null) {
                b = l2.val;
            }
            int num = a + b + temp;
            if(num <= 9) {
                res.val = num;
                temp = 0;
            } else {
                char[] chs = String.valueOf(num).toCharArray();
                res.val = chs[1] - '0';
                temp = chs[0] - '0';
            }
            if(l1 != null) {
                l1 = l1.next;
            }
            if(l2 != null) {
                l2 = l2.next;
            }
            if(l1!=null || l2 != null) {
                res.next = new ListNode();
                res = res.next;
            }
        }

        if(temp > 0) {
            res.next = new ListNode();
            res = res.next;
            res.val = temp;
        }

        return head;
    }


}
